﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
}

@model ThridGroup.ERP.DTO.ProductionSystem.CrewSchedulingDTO
@{
    Layout = null;
}
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>编辑排班计划</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="~/libs/scripts/layui-v2.5.6/layui/css/layui.css" rel="stylesheet" />
    <script src="~/libs/scripts/layui-v2.5.6/layui/layui.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div style="padding: 20px;">
        <form class="layui-form" lay-filter="crewSchedulingForm">
            <input type="hidden" name="id" value="@Model.Id">
            <div class="layui-form-item">
                <label class="layui-form-label">计划编号</label>
                <div class="layui-input-block">
                    <input type="text" name="planNumber" required lay-verify="required" placeholder="请输入计划编号" autocomplete="off" class="layui-input" value="@Model.PlanNumber">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">计划名称</label>
                <div class="layui-input-block">
                    <input type="text" name="planName" required lay-verify="required" placeholder="请输入计划名称" autocomplete="off" class="layui-input" value="@Model.PlanName">
                </div>
            </div>
            <div class="layui-form-item">
				<label class="layui-form-label">开始日期</label>
				<div class="layui-input-block">
					<input type="text" name="startTime" id="startTime" required lay-verify="required" placeholder="请选择开始日期" autocomplete="off" class="layui-input" value="@(Model.Id > 0 ? Model.StartTime.ToString("yyyy-MM-dd") : "")">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">结束日期</label>
				<div class="layui-input-block">
					<input type="text" name="endTime" id="endTime" required lay-verify="required" placeholder="请选择结束日期" autocomplete="off" class="layui-input" value="@(Model.Id > 0 ? Model.EndTime.ToString("yyyy-MM-dd") : "")">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">班组类型</label>
				<div class="layui-input-block">
					<select name="teamType" required lay-verify="required">
						<option value="">请选择班组类型</option>
						<option value="仓库" selected="@(Model.TeamType == "仓库")">仓库</option>
						<option value="机加工" selected="@(Model.TeamType == "机加工")">机加工</option>
						<option value="注塑" selected="@(Model.TeamType == "注塑")">注塑</option>
						<option value="组装" selected="@(Model.TeamType == "组装")">组装</option>
					</select>
				</div>
			</div>
            <div class="layui-form-item">
                <label class="layui-form-label">轮班方式</label>
                <div class="layui-input-block">
                    <input type="radio" name="shiftWay" value="白班" title="白班" lay-filter="shiftWayFilter" @(Model.ShiftWay == "白班" || Model.Id == 0 ? "checked" : "")>
                    <input type="radio" name="shiftWay" value="两班倒" title="两班倒" lay-filter="shiftWayFilter" @(Model.ShiftWay == "两班倒" ? "checked" : "")>
                    <input type="radio" name="shiftWay" value="三班倒" title="三班倒" lay-filter="shiftWayFilter" @(Model.ShiftWay == "三班倒" ? "checked" : "")>
                </div>
            </div>
            <div class="layui-form-item" id="productionWayContainer" style="display: none;">
                <label class="layui-form-label">倒班方式</label>
                <div class="layui-input-block">
                    <select name="productionWay" lay-filter="productionWayFilter">
                        <option value="">请选择倒班方式</option>
                        <option value="按天" selected="@(Model.ProductionWay == "按天")">按天</option>
                        <option value="按月" selected="@(Model.ProductionWay == "按月")">按月</option>
                        <option value="按季度" selected="@(Model.ProductionWay == "按季度")">按季度</option>
                        <option value="按年" selected="@(Model.ProductionWay == "按年")">按年</option>
                    </select>
                </div>
            </div>
            <div class="layui-form-item" id="numbersContainer" style="display: none;">
                <label class="layui-form-label">天数</label>
                <div class="layui-input-block">
                    <input type="number" name="numbers" placeholder="请输入天数" autocomplete="off" class="layui-input" value="@Model.Numbers">
                </div>
            </div>
            <div class="layui-form-item" id="documentStatusContainer">
                <label class="layui-form-label">单据状态</label>
                <div class="layui-input-block">
					<select name="documentStatus" lay-verify="required">
						<option value="草稿" selected="@(Model.DocumentStatus == "草稿")">草稿</option>
						<option value="已确定" selected="@(Model.DocumentStatus == "已确定")">已确定</option>
					</select>
                </div>
            </div>
            <div class="layui-form-item" style="text-align: center;">
                <button class="layui-btn" lay-submit lay-filter="submitForm">确定</button>
                <button type="button" class="layui-btn layui-btn-primary" id="btnCancelMain">取消</button>
            </div>
        </form>

        @if (Model.Id > 0)
        {
            <div id="sailingsSection">
                <hr />
                <div class="layui-card">
                    <div class="layui-card-header">班次</div>
                    <div class="layui-card-body">
                        <div style="margin-bottom: 10px;">
                            <button type="button" class="layui-btn layui-btn-sm" id="btnAddSailing"><i class="layui-icon">&#xe654;</i> 新增</button>
                        </div>
                        <table id="sailingsTable" lay-filter="sailingsTable"></table>
                    </div>
                </div>
            </div>
        }
    </div>

    <script type="text/html" id="sailingsTableBar">
        <a class="layui-btn layui-btn-xs" lay-event="edit">修改</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>

    <div id="sailingsForm" style="display: none; padding: 20px;">
		<form class="layui-form" lay-filter="sailingsForm">
			<input type="hidden" name="id">
			<input type="hidden" name="crewId">
			<div class="layui-form-item">
				<label class="layui-form-label">序号</label>
				<div class="layui-input-block">
					<input type="number" name="unitNum" required lay-verify="required|number" placeholder="请输入序号" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">班次名称</label>
				<div class="layui-input-block">
					<input type="text" name="className" required lay-verify="required" placeholder="请输入班次名称" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">开始时间</label>
				<div class="layui-input-block">
					<input type="text" name="begingTime" id="begingTime" required lay-verify="required" placeholder="请选择开始时间" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<label class="layui-form-label">结束时间</label>
				<div class="layui-input-block">
					<input type="text" name="overTime" id="overTime" required lay-verify="required" placeholder="请选择结束时间" autocomplete="off" class="layui-input">
				</div>
			</div>
			<div class="layui-form-item">
				<div class="layui-input-block">
					<button class="layui-btn" lay-submit lay-filter="submitSailingForm">确定</button>
					<button type="button" class="layui-btn layui-btn-primary" id="btnCancelSailing">取消</button>
				</div>
			</div>
		</form>
	</div>


    <script>
        layui.use(['table', 'form', 'layer', 'laydate'], function () {
            var table = layui.table;
            var form = layui.form;
            var layer = layui.layer;
            var laydate = layui.laydate;
            var $ = layui.$;

            var modelId = @Model.Id;

            laydate.render({ elem: '#startTime' });
            laydate.render({ elem: '#endTime' });

            // 动态显示逻辑初始化
            function initializeDynamicFields() {
                var shiftWay = $('input[name="shiftWay"]:checked').val();
                var numbersInput = $('input[name="numbers"]');
                var productionWaySelect = $('select[name="productionWay"]');

                if (shiftWay !== '白班') {
                    $('#productionWayContainer').show();
                    productionWaySelect.attr('lay-verify', 'required');
                    var productionWay = $('select[name="productionWay"]').val();
                    if (productionWay === '按天') {
                        $('#numbersContainer').show();
                        numbersInput.attr('lay-verify', 'required|number');
                    } else {
                        $('#numbersContainer').hide();
                        numbersInput.removeAttr('lay-verify');
                    }
                } else {
                    $('#productionWayContainer').hide();
                    productionWaySelect.removeAttr('lay-verify');
                    $('#numbersContainer').hide();
                    numbersInput.removeAttr('lay-verify');
                }

                if (modelId > 0) {
                    $('#documentStatusContainer').show();
                } else {
                    $('#documentStatusContainer').hide();
                }
            }

            initializeDynamicFields();

            if (modelId == 0) {
                var planNumber = "PLAN" + new Date().getTime();
                $('input[name="planNumber"]').val(planNumber);
                $('select[name="documentStatus"]').val('草稿');
                form.render('select');
            }

            form.on('radio(shiftWayFilter)', function (data) {
                var formElem = $(data.elem).closest('form');
                var numbersInput = formElem.find('input[name="numbers"]');
                var productionWaySelect = formElem.find('select[name="productionWay"]');

                if (data.value === '白班') {
                    formElem.find('#productionWayContainer').hide().find('select').val('');
                    productionWaySelect.removeAttr('lay-verify');
                    formElem.find('#numbersContainer').hide().find('input').val('');
                    numbersInput.removeAttr('lay-verify');
                } else {
                    formElem.find('#productionWayContainer').show();
                     productionWaySelect.attr('lay-verify', 'required');
                }
                form.render('select');
            });

            form.on('select(productionWayFilter)', function (data) {
                var formElem = $(data.elem).closest('form');
                var numbersInput = formElem.find('input[name="numbers"]');
                if (data.value === '按天') {
                    formElem.find('#numbersContainer').show();
                    numbersInput.attr('lay-verify', 'required|number');
                } else {
                    formElem.find('#numbersContainer').hide().find('input').val('');
                    numbersInput.removeAttr('lay-verify');
                }
            });

            form.on('submit(submitForm)', function (data) {
                var submitData = data.field;

                if (new Date(submitData.startTime) > new Date(submitData.endTime)) {
                    layer.msg('结束日期不能小于开始日期');
                    return false;
                }

                var url = submitData.id > 0 ? '/CrewScheduling/UpdateCrewScheduling' : '/CrewScheduling/AddCrewScheduling';
                var method = submitData.id > 0 ? 'PUT' : 'POST';

                if (!submitData.id || submitData.id == '0') {
                    submitData.id = 0;
                } else {
                    submitData.id = parseInt(submitData.id);
                }
                submitData.numbers = submitData.numbers ? parseInt(submitData.numbers) : 0;

                $.ajax({
                    url: url,
                    type: method,
                    contentType: 'application/json',
                    data: JSON.stringify(submitData),
                    success: function (res) {
                        layer.msg('保存成功', { icon: 1, time: 1000 }, function(){
                             parent.layui.table.reload('crewSchedulingTable');
                             var index = parent.layer.getFrameIndex(window.name);
                             parent.layer.close(index);
                        });
                    },
                    error: function () {
                        layer.msg('保存失败');
                    }
                });
                return false;
            });

            $('#btnCancelMain').on('click', function() {
                closeWindow();
            });

            var sailingLayerIndex;
            // 班次相关逻辑
            if (modelId > 0) {
                table.render({
                    elem: '#sailingsTable',
                    url: '/CrewScheduling/ShowSailings?id=' + modelId,
                    cols: [[
                        { field: 'unitNum', title: '序号', width: 80, sort: true },
                        { field: 'className', title: '班次名称' },
                        { field: 'begingTime', title: '开始时间', templet: "<div>{{layui.util.toDateString(d.begingTime, 'HH:mm:ss')}}</div>" },
                        { field: 'overTime', title: '结束时间', templet: "<div>{{layui.util.toDateString(d.overTime, 'HH:mm:ss')}}</div>" },
                        { title: '操作', toolbar: '#sailingsTableBar', width: 150 }
                    ]],
                    parseData: function (res) {
                        return {
                            "code": res.code,
                            "msg": res.msg,
                            "count": res.data.length,
                            "data": res.data
                        };
                    }
                });

                $('#btnAddSailing').on('click', function () {
                    openSailingForm('添加班次', null, modelId);
                });

                table.on('tool(sailingsTable)', function (obj) {
                    var data = obj.data;
                    if (obj.event === 'edit') {
                        openSailingForm('修改班次', data, data.crewId);
                    } else if (obj.event === 'del') {
                        layer.confirm('确定删除此班次吗？', function (index) {
                            $.ajax({
                                url: '/CrewScheduling/DeleteSailings',
                                type: 'DELETE',
                                contentType: 'application/json',
                                data: JSON.stringify([data.id]),
                                success: function (res) {
                                    layer.msg('删除成功');
                                    obj.del();
                                },
                                error: function () {
                                    layer.msg('删除失败');
                                }
                            });
                            layer.close(index);
                        });
                    }
                });

                form.on('submit(submitSailingForm)', function(data){
                    var submitData = data.field;

                    if (submitData.begingTime > submitData.overTime) {
                        layer.msg('结束时间不能小于开始时间');
                        return false;
                    }

                    var url = submitData.id && submitData.id != '0' ? '/CrewScheduling/UpdateSailings' : '/CrewScheduling/AddSailings';
                    var method = submitData.id && submitData.id != '0' ? 'PUT' : 'POST';

                    var now = new Date();
                    var datePart = layui.util.toDateString(now, 'yyyy-MM-dd');
                    submitData.begingTime = datePart + ' ' + submitData.begingTime;
                    submitData.overTime = datePart + ' ' + submitData.overTime;

                    if (!submitData.id || submitData.id == '0') submitData.id = 0;
                    else submitData.id = parseInt(submitData.id);
                    submitData.crewId = parseInt(submitData.crewId);
                    submitData.unitNum = parseInt(submitData.unitNum);

                    $.ajax({
                        url: url,
                        type: method,
                        contentType: 'application/json',
                        data: JSON.stringify(submitData),
                        success: function(res){
                            layer.close(sailingLayerIndex);
                            layer.msg('保存成功');
                            table.reload('sailingsTable');
                        },
                        error: function(){
                            layer.msg('保存失败');
                        }
                    });
                    return false;
                });

                $('#sailingsForm').on('click', '#btnCancelSailing', function(){
                    layer.close(sailingLayerIndex);
                });
            }

            function openSailingForm(title, sailingData, crewId) {
                sailingLayerIndex = layer.open({
					type: 1,
					title: title,
					area: ['500px', '400px'],
					content: $('#sailingsForm'),
					success: function(layero, index){
						var formElem = $(layero).find('form');
                        formElem[0].reset();
						if(sailingData) {
							sailingData.begingTime = layui.util.toDateString(sailingData.begingTime, 'HH:mm:ss');
							sailingData.overTime = layui.util.toDateString(sailingData.overTime, 'HH:mm:ss');
							form.val('sailingsForm', sailingData);
						}
						form.val('sailingsForm', { crewId: crewId });
						
						laydate.render({ elem: $(layero).find('input[name="begingTime"]'), type: 'time' });
						laydate.render({ elem: $(layero).find('input[name="overTime"]'), type: 'time' });

						form.render(null, 'sailingsForm');
					}
				});
            }

             function closeWindow(){
                var index = parent.layer.getFrameIndex(window.name);
                parent.layer.close(index);
             }
        });
    </script>
</body>
</html>
